package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@Controller
@ResponseBody
@RequestMapping("/login")
public class loginMobileController {
    @Reference
    MemberService memberService;

    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/check")
    public Result check(@RequestBody Map<String,Object> map, HttpServletResponse response){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if(validateCode!=null&&validateCode.equals(code)){
            Member member = new Member();
            member.setPhoneNumber(telephone);
            Integer i = memberService.find(member);
            if(i==null){
                //不是会员,注册为会员
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //把登录信息存放到cookie中
            Cookie cookie = new Cookie("member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(30*24*60*60);
            response.addCookie(cookie);
            return new Result(true,"");
        }else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
